package com.jinlongchen.servlet;

import com.jinlongchen.util.DBUtil;
import com.jinlongchen.model.User;
import com.jinlongchen.service.AlbumService;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;
import java.sql.*;
import java.util.UUID;

@MultipartConfig
@WebServlet("/new-album")
public class NewAlbumServlet extends HttpServlet {
    private final AlbumService albumService = new AlbumService();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        User currentUser =(User) req.getSession().getAttribute("currentUser");
        //后端有责任进行权限验证，要求用户必须登陆后才能使用该资源
        if (currentUser == null){
            throw new ServletException("用户未登录");
        }

        req.setCharacterEncoding("utf-8");
        String name = req.getParameter("name");

        //图片是以二进制形式传递上来的，我们必须要通过part去拿
        Part coverPart = req.getPart("cover");
        System.out.println(coverPart.getSubmittedFileName()); //提交文件名
        System.out.println(coverPart.getInputStream()); //真正的数据必须通过这个输入流进行读取

        //把图片保存成本地的一个文件
        //我们需要一个 FileOutputStream
        int i = coverPart.getSubmittedFileName().lastIndexOf('.');
        String suffix = coverPart.getSubmittedFileName().substring(i);

        ServletContext servletContext = req.getServletContext();
        String uuid = UUID.randomUUID().toString();
        String coverPath = "/img/" + uuid + suffix;
        String filename = servletContext.getRealPath(coverPath);

        int aid;

        try (Connection c = DBUtil.getConnection()){
            aid = albumService.save(c,currentUser.uid,name,coverPart.getInputStream(),coverPath,filename);
        }catch (SQLException exc){
            throw new ServletException(exc);
        }

//        try (OutputStream os = new FileOutputStream(filename)){
//            InputStream is = coverPart.getInputStream();
//            byte[] buf = new byte[1024];
//
//            while(true){
//                int len = is.read(buf);
//                if (len == -1){
//                    break;
//                }
//                os.write(buf,0,len);
//            }
//            os.flush();
//        }
//
//        //保存数据库
//        //name,coverPath
//        int aid;
//        try (Connection c = DBUtil.getConnection()){
//            String sql = "INSERT INTO album (name,cover,uid) VALUES (?,?,?)";
//            try (PreparedStatement s = c.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)){
//                s.setString(1,name);
//                s.setString(2,coverPath);
//                s.setInt(3,currentUser.uid);
//
//                s.executeUpdate();
//                try (ResultSet rs = s.getGeneratedKeys()){
//                    rs.next();
//
//                    aid = rs.getInt(1);
//
//                }
//            }
//        }catch (SQLException exc){
//            throw new ServletException(exc);
//        }

        resp.sendRedirect("/album-editor.html?aid="+aid);
    }
}
